// 连接mongodb
const mongoose = require('mongoose')
const { Schema } = mongoose

const url = 'mongodb://localhost:27017'
const dataBase = 'blog'
mongoose
  .connect(`${url}/${dataBase}`)
  .then((res) => {
    console.log('mongodb connected success')
  })
  .catch((err) => {
    console.error('connection error' + err)
  })

const db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error:'))

// 定义schema
const userSchema = new Schema({
  username: String,
  password: String,
  realname: String,
})

// 定义model user 会 自动对应 mongodb数据库表中的 users表
const User = mongoose.model('user', userSchema)

!(async () => {
  // 查询用户
  const res = await User.find({
    realname: /四/, // 正则表达式实现模糊查询
  })
  console.log(res, '--- res 41 ---')

  // 新建用户 先实例化后在保存
  const newUser = new User({
    username: 'test',
    password: '123456',
    realname: '测试人员',
  })
  const res2 = await newUser.save()
  console.log(res2, '--- res 42 保存 ---')

  // 查询详情用户
  const res3 = await User.findById('67316934731f750c57082437')
  console.log(res3, '--- res3 查询单个详情  ---')

  // 更新用户
  const res4 = await User.updateOne(
    { _id: '67316934731f750c57082437' },
    { realname: '李四四' }
  )
  console.log(res4, '--- res4 更新  ---')

  // 删除用户
  const res5 = await User.deleteOne({ _id: '673174e225c2e08f2e9443f6' })
  console.log(res5, '--- res5 删除  ---')
})()
// 关闭连接
// db.close()
